<script setup lang="ts">
  import { HMessage, HMessageBox } from '@/components/common/message'
  import infoTip from '@/config/info-tip'
  import {
    useDetectFieldConnect,
    useGetDetectCustomFieldOptions,
    useGetDetectFieldConnectDetail,
  } from '@/services/pages/return-factory/useModule'
  import { ElForm, ElFormItem, FormInstance, ElSelect, ElOption, ElSwitch } from 'element-plus'
  import _ from 'lodash'
  import { ref, watch } from 'vue'

  const { options, getOptionsParams, getOptionsLoading, getOptions } =
    useGetDetectCustomFieldOptions()
  const { form, connectLoading, connect, resetForm } = useDetectFieldConnect()
  const { fieldConnectDetail, getDetailLoading, getDetail } = useGetDetectFieldConnectDetail()

  defineOptions({
    name: 'ReturnFactoryDetectFieldConnectModal',
  })

  const props = defineProps({
    moduleId: {
      type: String,
      required: true,
    },
    fieldConnectId: {
      type: String,
      default: () => '',
    },
  })

  const emits = defineEmits<{
    (e: 'update'): void
  }>()

  // 弹窗显示状态
  const visible = defineModel('visible', { type: Boolean, default: false })

  // 表单组件实例
  const formInstance = ref<FormInstance | null>(null)

  // 表单校验规则
  const rules = ref({
    repairFieldId: [{ required: true, message: '请选择字段', trigger: ['change', 'blur'] }],
    mobileShow: [
      { required: true, message: '移动端是否显示不能为空', trigger: ['change', 'blur'] },
    ],
    required: [{ required: true, message: '是否必填不能为空', trigger: ['change', 'blur'] }],
  })

  /**
   * 获取检测自定字段
   */
  const handleGetDetectFieldOptions = _.debounce((keyword: string) => {
    if (getOptionsParams.value.name !== keyword) {
      getOptionsParams.value.name = keyword
      getOptions()
    }
  }, 600)

  /**
   * 隐藏弹窗
   */
  const hideDialog = () => {
    resetForm()
    visible.value = false
  }

  /**
   * 确定事件
   */
  const onConfirm = async () => {
    if (formInstance.value) {
      try {
        await formInstance.value.validate()
        form.value.repairModuleId = props.moduleId
        const res = await connect()
        if (res.code === 20000) {
          HMessage.success('关联成功')
          hideDialog()
          emits('update')
          return
        }
        HMessageBox.error(
          infoTip.returnFactory.module.detect_field_connect_err_code[res.code] || res.message,
        )
      } catch (error) {
        // error
      }
    }
  }

  watch(
    visible,
    async (value) => {
      if (value) {
        getOptions()

        if (props.fieldConnectId) {
          await getDetail(props.fieldConnectId)
          form.value = fieldConnectDetail.value
        }
      }
    },
    { immediate: true },
  )
</script>

<template>
  <h-dialog
    v-model="visible"
    title="检测字段关联"
    :loading="connectLoading || getDetailLoading"
    @close="hideDialog"
  >
    <el-form
      ref="formInstance"
      :model="form"
      label-position="top"
      inline-message
      :rules="rules"
      class="modal_form_content"
    >
      <!-- 关联字段 -->
      <el-form-item label="关联字段" prop="repairFieldId">
        <el-select
          v-model="form.repairFieldId"
          placeholder="请选择字段"
          :loading="getOptionsLoading"
          filterable
          :filter-method="handleGetDetectFieldOptions"
        >
          <el-option
            v-for="(field, fieldIndex) in options"
            :key="fieldIndex"
            :label="field.name"
            :value="field.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <div class="same_line">
        <!-- 移动端是否显示 -->
        <el-form-item label="移动端是否显示" class="swtich-container-size-small" prop="mobileShow">
          <el-switch v-model="form.mobileShow" size="small"></el-switch>
          <div class="text">{{ form.mobileShow ? '显示' : '隐藏' }}</div>
        </el-form-item>

        <!-- 是否必填 -->
        <el-form-item label="是否必填" class="swtich-container-size-small" prop="required">
          <el-switch v-model="form.required" size="small"></el-switch>
          <div class="text">{{ form.required ? '必填' : '不必填' }}</div>
        </el-form-item>
      </div>
    </el-form>

    <template #footer>
      <h-button type="primary" is-modal @click="onConfirm">确定</h-button>
      <h-button is-modal @click="hideDialog">取消</h-button>
    </template>
  </h-dialog>
</template>
